<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-28 00:33:21
 * Desc:
 */

namespace app\admin\service;

use app\base\service\BaseService;
use app\api\service\GoodsService as apiGoodsService;
use app\base\model\goods\{GoodsBaseInfo,
    GoodsIntroduceInfo,
    GoodsKeywordInfo,
    GoodsPlatformInfo,
    GoodsConfigInfo};
use app\base\model\system\SystemConfig;
use app\core\cache\{RedisCache, RedisKeys};
use app\core\exception\BusinessException;
use app\core\exception\ErrorCode;
use app\core\log\Log4dd;
use Think\Db;

class GoodsService extends BaseService
{

    public static function addNewGoods($data)
    {
        Log4dd::info('新增商品 first', func_get_args());
        Db::startTrans();

        try {

            if (!isset($data['base_info'])) {
                Db::rollback();
                throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS);
            }

            $need_wish_coin = $data['base_info']['need_wish_coin'];

            //计算发起兑换需消耗的心愿币数量=商品折扣比例*市场价
            if (empty($need_wish_coin)) {
                $need_wish_coin = self::getNeedWishCoin($data['platform_info']['platform_price']);
            }


            if (empty($need_wish_coin) || $need_wish_coin < 0) {
                Db::rollback();
                throw new BusinessException(ErrorCode::COMMON_INVALID_PARAMS, '发起兑换需消耗的心愿币数量有误');
            }

            $data['base_info']['need_wish_coin'] = $need_wish_coin;

            $need_people = $data['base_info']['need_people'];

            if (empty($need_people)) {
                $need_people = self::getDefaultNeedPeople();
            }

            if (empty($need_people) || $need_people < 0) {
                Db::rollback();
                throw new BusinessException(ErrorCode::COMMON_INVALID_PARAMS, '兑换需参与的人数有误');
            }

            $data['base_info']['need_people'] = $need_people;

            $people_get_wish_coin = $data['base_info']['people_get_wish_coin'];

            //帮付款赠送心愿币=帮付款金额 * 心愿值赠送系数  帮付款金额 = 市场价 / 成单人数
            if (empty($people_get_wish_coin)) {
                $people_get_wish_coin = self::getPeopleGetWishCoin($data['platform_info']['platform_price'],
                    $need_people);
            }

            if (empty($people_get_wish_coin) || $people_get_wish_coin < 0) {
                Db::rollback();
                throw new BusinessException(ErrorCode::COMMON_INVALID_PARAMS, '参与的用户每人支付后可获得的心愿币数量有误');
            }

            $data['base_info']['people_get_wish_coin'] = $people_get_wish_coin;

            Log4dd::info('新增商品 base', $data['base_info']);
            $base_model = GoodsBaseInfo::create($data['base_info']);
            if (!$base_model->goods_id) {
                Db::rollback();
                throw new BusinessException(ErrorCode::DATA_OPERATE_FAIL, '基础信息配置有误');
            }

            $goods_id = $base_model->goods_id;

            $data['platform_info']['goods_id'] = $goods_id;
            Log4dd::info('新增商品 platform', $data['platform_info']);
            $platform_model = GoodsPlatformInfo::create($data['platform_info']);

            if (!$platform_model) {
                Db::rollback();
                throw new BusinessException(ErrorCode::DATA_OPERATE_FAIL, '第三方信息配置有误');
            }

            $introduce_model = new GoodsIntroduceInfo();

            $introduce_content_info = $data['introduce_info']['introduce_content_info'];
            $content_num = 0;
            if ($introduce_content_info && is_array($introduce_content_info)) {
                $content_urls = [];
                foreach ($introduce_content_info as $content_item) {
                    $content_num++;
                    $content_urls[] = [
                        'goods_id' => $goods_id,
                        'introduce_type' => GoodsIntroduceInfo::INTRODUCE_TYPE_CONTENT,
                        'introduce_url' => $content_item,
                        'resource_type' => 'image',
                        'sort_num' => $content_num,
                        'status' => 1,
                    ];
                }

                if ($content_urls) {
                    Log4dd::info('新增商品 content_urls', $content_urls);
                    $content_res = $introduce_model->saveAll($content_urls);
                    if (!$content_res) {
                        Db::rollback();
                        throw new BusinessException(ErrorCode::DATA_OPERATE_FAIL, '商品详情图配置有误');
                    }
                }
            }

            $carousel_num = 0;
            $introduce_carousel_info = $data['introduce_info']['introduce_carousel_info'];
            if ($introduce_carousel_info && is_array($introduce_carousel_info)) {
                $carousel_urls = [];
                foreach ($introduce_carousel_info as $carousel_item) {
                    $carousel_num++;
                    $carousel_urls[] = [
                        'goods_id' => $goods_id,
                        'introduce_type' => GoodsIntroduceInfo::INTRODUCE_TYPE_CAROUSEL,
                        'introduce_url' => $carousel_item,
                        'resource_type' => 'image',
                        'sort_num' => $carousel_num,
                        'status' => 1,
                    ];
                }

                if ($carousel_urls) {
                    Log4dd::info('新增商品 carousel_urls', $carousel_urls);
                    $carousel_res = $introduce_model->saveAll($carousel_urls);
                    if (!$carousel_res) {
                        Db::rollback();
                        throw new BusinessException(ErrorCode::DATA_OPERATE_FAIL, '商品轮播图配置有误');
                    }
                }
            }


            if ($data['keyword_info']['keywords']) {
                $data['keyword_info']['goods_id'] = $goods_id;
                $keywords_name = explode(',', $data['keyword_info']['keywords']);
                $keyword_data = [];
                foreach ($keywords_name as $keyword) {
                    $keyword_data[] = [
                        'goods_id' => $goods_id,
                        'keyword_name' => $keyword
                    ];
                }

                if ($keyword_data) {
                    $keyword_model = new GoodsKeywordInfo();
                    Log4dd::info('新增商品 keyword_data', $keyword_data);
                    $keyword_res = $keyword_model->saveAll($keyword_data);
                    if (!$keyword_res) {
                        Db::rollback();
                        throw new BusinessException(ErrorCode::DATA_OPERATE_FAIL, '关键字信息配置有误');
                    }
                }
            }

            $data['config_info']['goods_id'] = $goods_id;
            Log4dd::info('新增商品 config_info', $data['config_info']);
            $config_model = GoodsConfigInfo::create($data['config_info']);

            if (!$config_model) {
                Db::rollback();
                throw new BusinessException(ErrorCode::DATA_OPERATE_FAIL, '配置信息有误');
            }

            GoodsBaseInfo::delGoodsInfoCache($goods_id);
            GoodsBaseInfo::delApiGoodsListCache();

            Db::commit();
            return true;
        } catch (BusinessException $e) {
            Db::rollback();
            Log4dd::info("新增商品失败:{$e->getMessage()}", func_get_args(), $e);
            return false;
        }

    }

    public static function updateGoods($goods_id, $data)
    {
        Log4dd::info('修改商品 first', func_get_args());
        Db::startTrans();

        try {

            if (!isset($data['base_info'])) {
                Db::rollback();
                throw new BusinessException(ErrorCode::COMMON_LACK_PARAMS);
            }

            $need_wish_coin = $data['base_info']['need_wish_coin'];

            //计算发起兑换需消耗的心愿币数量=商品折扣比例*市场价
            if (empty($need_wish_coin)) {
                $need_wish_coin = self::getNeedWishCoin($data['platform_info']['platform_price']);
            }


            if (empty($need_wish_coin) || $need_wish_coin < 0) {
                Db::rollback();
                throw new BusinessException(ErrorCode::COMMON_INVALID_PARAMS, '发起兑换需消耗的心愿币数量有误');
            }

            $data['base_info']['need_wish_coin'] = $need_wish_coin;

            $need_people = $data['base_info']['need_people'];

            if (empty($need_people)) {
                $need_people = self::getDefaultNeedPeople();;
            }

            if (empty($need_people) || $need_people < 0) {
                Db::rollback();
                throw new BusinessException(ErrorCode::COMMON_INVALID_PARAMS, '兑换需参与的人数有误');
            }

            $data['base_info']['need_people'] = $need_people;

            $people_get_wish_coin = self::getPeopleGetWishCoin($data['platform_info']['platform_price'], $need_people);

            if (empty($people_get_wish_coin) || $people_get_wish_coin < 0) {
                Db::rollback();
                throw new BusinessException(ErrorCode::COMMON_INVALID_PARAMS, '参与的用户每人支付后可获得的心愿币数量有误');
            }

            $data['base_info']['people_get_wish_coin'] = $people_get_wish_coin;

            Log4dd::info('修改商品 base', [$goods_id, $data['base_info']]);
            GoodsBaseInfo::where('goods_id', $goods_id)->update($data['base_info']);

            Log4dd::info('修改商品 platform', [$goods_id, $data['platform_info']]);
            GoodsPlatformInfo::where('goods_id', $goods_id)->update($data['platform_info']);

            $introduce_model = new GoodsIntroduceInfo();

            $introduce_content_info = $data['introduce_info']['introduce_content_info'];
            $content_num = 0;
            if ($introduce_content_info && is_array($introduce_content_info)) {
                GoodsIntroduceInfo::where('goods_id', $goods_id)->where('introduce_type', GoodsIntroduceInfo::INTRODUCE_TYPE_CONTENT)->delete();
                $content_urls = [];
                foreach ($introduce_content_info as $content_item) {
                    $content_num++;
                    $content_urls[] = [
                        'goods_id' => $goods_id,
                        'introduce_type' => GoodsIntroduceInfo::INTRODUCE_TYPE_CONTENT,
                        'introduce_url' => $content_item,
                        'resource_type' => 'image',
                        'sort_num' => $content_num,
                        'status' => 1,
                    ];
                }

                if ($content_urls) {
                    $content_res = $introduce_model->saveAll($content_urls);
                    if (!$content_res) {
                        Db::rollback();
                        throw new BusinessException(ErrorCode::DATA_OPERATE_FAIL, '商品详情图配置有误');
                    }
                }
            }

            $carousel_num = 0;
            $introduce_carousel_info = $data['introduce_info']['introduce_carousel_info'];
            if ($introduce_carousel_info && is_array($introduce_carousel_info)) {
                GoodsIntroduceInfo::where('goods_id', $goods_id)->where('introduce_type', GoodsIntroduceInfo::INTRODUCE_TYPE_CAROUSEL)->delete();

                $carousel_urls = [];
                foreach ($introduce_carousel_info as $carousel_item) {
                    $carousel_num++;
                    $carousel_urls[] = [
                        'goods_id' => $goods_id,
                        'introduce_type' => GoodsIntroduceInfo::INTRODUCE_TYPE_CAROUSEL,
                        'introduce_url' => $carousel_item,
                        'resource_type' => 'image',
                        'sort_num' => $carousel_num,
                        'status' => 1,
                    ];
                }

                if ($carousel_urls) {
                    $carousel_res = $introduce_model->saveAll($carousel_urls);
                    if (!$carousel_res) {
                        Db::rollback();
                        throw new BusinessException(ErrorCode::DATA_OPERATE_FAIL, '商品轮播图配置有误');
                    }
                }
            }


            if ($data['keyword_info']['keywords']) {
                $data['keyword_info']['goods_id'] = $goods_id;
                $keywords_name = explode(',', $data['keyword_info']['keywords']);
                $keyword_data = [];
                foreach ($keywords_name as $keyword) {
                    $keyword_data[] = [
                        'goods_id' => $goods_id,
                        'keyword_name' => $keyword
                    ];
                }

                if ($keyword_data) {
                    $keyword_model = new GoodsKeywordInfo();
                    GoodsKeywordInfo::where('goods_id', $goods_id)->delete();
                    Log4dd::info('修改商品 keyword_data', $keyword_data);
                    $keyword_res = $keyword_model->saveAll($keyword_data);
                    if (!$keyword_res) {
                        Db::rollback();
                        throw new BusinessException(ErrorCode::DATA_OPERATE_FAIL, '关键字信息配置有误');
                    }
                }
            }

            Log4dd::info('修改商品 config_info', $data['config_info']);

            $config_model = GoodsConfigInfo::get($goods_id);

            if ($config_model) {
                GoodsConfigInfo::where('goods_id', $goods_id)->update($data['config_info']);
            } else {
                $data['config_info']['goods_id'] = $goods_id;
                Log4dd::info('修改商品 config_info', $data['config_info']);
                GoodsConfigInfo::create($data['config_info']);
            }

            GoodsBaseInfo::delGoodsInfoCache($goods_id);
            GoodsBaseInfo::delApiGoodsListCache();

            Db::commit();
            return true;
        } catch (BusinessException $e) {
            Db::rollback();
            Log4dd::info("修改商品失败:{$e->getMessage()}", func_get_args(), $e);
            return false;
        }
    }

    public static function getNeedWishCoin($price)
    {
        $goods_sale_ratio = SystemConfig::getSystemConfigByName('goods_sale_ratio',
            config('goods_default_config.default_goods_sale_ratio'));

        return ceil($goods_sale_ratio * $price);
    }

    public static function getDefaultNeedPeople()
    {
        return SystemConfig::getSystemConfigByName('default_group_success_need_people_num',
            config('goods_default_config.default_group_success_need_people_num'));
    }

    public static function getPeopleGetWishCoin($price, $need_people)
    {
        if ($need_people == 0) {
            return 0;
        }

        //获取需要支付的金额
        $need_pay_money = apiGoodsService::calculateNeedPayMoney(['group_total_price' => $price, 'need_people' => $need_people]);

        $wish_coin = apiGoodsService::calculateCanGetWishCoinNum($need_pay_money);

        return $wish_coin;
    }


}